/*获取当前图书的目录*/
import { getLib,getBooks } from '../api/lib'
interface Chapter{
    chapterID:number
    pageIndex:number
    pageCount:number
}
interface getCategory{
    action: string
    consumeType:number
    platform: number
    deviceType: string
    deviceVersion: string
    channelId: number
    platformSource: string
    fromPaltform: string
    deviceSerialNo: string
    clientVersionNo: string
    epubID: string
    token?: string
    wordSize: number
    style: number
}
class Gategory{
    public mediaId:string
    public _MediaPageInfo:any
    public descs:string='' 
    public coverPic:string=''
    public chapter!:Chapter
    public pageTitle:string=''
    public pageNumber:number=1    
    readerContent:HTMLElement
    element:HTMLElement
    pagetit:HTMLElement
    pagenum:HTMLElement     
    constructor(mediaId:string){
        this.mediaId=mediaId
        this.element=document.getElementById('menu_gategory_list')!
        this.readerContent=document.getElementById('detail_con')!
        this.pagetit=document.getElementById('page_info_tit')!
        this.pagenum=document.getElementById('page_info_num')!
        console.log('this.chapter',this.chapter)
    }
    get ChapterIDs(){//只读，仅返回全部单元，pageCount为本单元共几页
        return this._MediaPageInfo.ChapterIDs
    }
    get contents(){
        /*只读，仅返回全部子章节，pageCount为本章节从本书第几页开始，htmlPage为本章节从哪个索引开始【默认为0】，最大值小于本单元总页数*/
        return this._MediaPageInfo.contents
    }
    getCategory(){        
        let _this=this
        let params:getCategory={
            action: 'getPcMediaInfo',
            consumeType: 1,
            platform: 3,
            deviceType: 'Android',
            deviceVersion: '5.0.0',
            channelId: 70000,
            platformSource: 'DDDS-P',
            fromPaltform: 'ds_android',
            deviceSerialNo: 'html5',
            clientVersionNo: '5.8.4',
            epubID: _this.mediaId,
            token: '',
            wordSize: 2,
            style: 2
        }
        getLib(params).then((res:any) => {
            if(res.status==200){
                let resData=res.data.data;
                //console.log(resData);                
                _this._MediaPageInfo=JSON.parse(resData.mediaInfo);//目录的数据
                _this.descs=resData.mediaVo.descs;//本书介绍
                _this.coverPic=resData.mediaVo.coverPic;//封面
                document.title=resData.mediaVo.title;
                console.log(_this._MediaPageInfo);
                //console.log(_this.descs);             
                if(_this.contents.length>0){
                    _this.viewLib();//展示书的章节
                    _this.getList();//切换单元章节
                    _this.viewDesc();//展示书的介绍
                    _this.appendBtn();//显示翻页按钮
                }                
            }
        });
    }
    viewLib(){//展示书的章节
        let _this=this;
        let tmpl = (contents: any) => `
            ${contents.map((item: { level: any; ChapterID: any; htmlPage: any; Label: any;pageCount:number }) => `
                <li><span class="level_${item.level}" data-chapterid="${item.ChapterID}" data-htmlpage="${item.htmlPage}">${item.Label}</span><em>${item.pageCount}</em></li>
            `).join('')}
        `;
        _this.element.innerHTML=tmpl(_this.contents);
    }
    viewDesc(){//展示书的介绍
        let _this=this;
        _this.readerContent.innerHTML=`<div class="book_con">
        <div class="book_img" data-src="${_this.coverPic}"><img src="${_this.coverPic}"></div>
        <div class="book_desc">${_this.descs}</div>
        </div>`;
    }
    getDetails(epuId:string,chapterID:number,pageIndex:number){//获取当前页内容
        let _this=this
        let params={
            action:'getPcChapterInfo',
            epubID:epuId,
            consumeType:1,
            platform:3,
            deviceType:"Android",
            deviceVersion:"5.0.0",
            channelId:7000,
            platformSource:"DDDS-P",
            fromPaltform:"ds_android",
            deviceSerialNo:"html5",
            clientVersionNo:"5.8.4",
            token:"",
            chapterID:chapterID,
            pageIndex:pageIndex,//默认从0开始，最大数小于本单元总页数
            locationIndex:0,//不要更改，破解之关键所在
            wordSize:2,
            style:2,
            autoBuy:0,
            chapterIndex:""
        }                
        getBooks(params).then((res:any) => {
            if(res.status==200){
                let resData=res.data.data;
                //console.log(resData);
                let chapterInfo=JSON.parse(resData.chapterInfo);
                //console.log('chapterInfo',chapterInfo);
                _this.getChapter(chapterID,pageIndex);
                if(chapterInfo.code==0){/*当code等于0时为正常状态，显示内容*/
                    _this.readerContent.innerHTML=chapterInfo.snippet;//更新内容                   
                   _this.viewPagenum();//填充页码
                   _this.viewPagetitle(chapterID,pageIndex);
                }
                
            }
        });
    }
    appendBtn(){//翻页按钮
        let _this=this;
        let btnPrev=document.getElementById('btn_prev') as HTMLElement;
        btnPrev.addEventListener('click',function(){//切换上一页
          _this.handlePrev();  
        })
        let btnNext=document.getElementById('btn_next') as HTMLElement;
        btnNext.addEventListener('click',function(){//切换下一页
            //console.log('切换下一页')
            _this.handleNext();  
        })
    }
    getList(){//获取左侧目录并绑定事件
        let _this=this;
        let mylist: NodeList = document.querySelectorAll('#menu_gategory_list li');
        mylist.forEach((item,index)=>{
            let spanProp=item.childNodes[0]['dataset'];//获取自定义属性的值          
            //给每个li绑定事件
            item.addEventListener('click',function(){
                //console.log('单元：',item.childNodes[0]['innerText']);
                let chapterid=parseInt(spanProp['chapterid']);//获取单元id
                let htmlpage=parseInt(spanProp['htmlpage']);//获取当前单元第1页的pageIndex                
                _this.pageTitle=item.childNodes[0]['innerText'];//获取本章节标题
                _this.pageNumber=parseInt(item.childNodes[1]['innerText'])//获取页码
                _this.getDetails(_this.mediaId,chapterid,htmlpage);//获取当前单元第1页的内容 
            })            
        })
    }
    getChapter(chapterID:number,pageIndex:number){//返回本单元信息
        let _this=this;
        let currChapter=_this.ChapterIDs.find((item: { ChapterID: number })=>item.ChapterID==chapterID);//获取本单元总页数等信息
        console.log('currChapter',currChapter);   
        _this.chapter={
            chapterID:chapterID,            
            pageCount:currChapter.pageCount,
            pageIndex:pageIndex
        };
        console.log('_this.chapter',_this.chapter);
    }
    viewPagenum(){//当前在书的第几页
        let _this=this;
        _this.pagenum.innerText=_this.pageNumber.toString();//填充页码
    }
    viewPagetitle(ChapterID:number,pageIndex:number){//当前单元标题名称        
        let _this=this;
        let currContent=_this.contents.find((item: { ChapterID: number; htmlPage: number })=>item.ChapterID==ChapterID && item.htmlPage==pageIndex);
        //console.log('currContent',currContent);
        if(currContent){
            _this.pageTitle=currContent.Label;//当前单元标题
            _this.pagetit.innerText=_this.pageTitle;//填充页面标题
        }
        
    }
    handleNext(){//下一页
        let _this=this;
        (document.getElementById('btn_prev') as HTMLElement).style.display='block'; //显示上一页按钮
        if(this.chapter){            
            let nextPageIndex=_this.chapter.pageIndex+1;//下一页的pageIndex
            _this.pageNumber=_this.pageNumber+1;//页码加1
            if(_this.chapter.chapterID<_this.ChapterIDs.length-1){//仅在单元数之内
                  
                if(nextPageIndex<_this.chapter.pageCount){
                    //本单元的下一页
                    _this.getDetails(_this.mediaId,_this.chapter.chapterID,nextPageIndex);
                }else{
                    //下一个单元的第1页
                    let nextChapter=_this.chapter.chapterID+1;
                    _this.getDetails(_this.mediaId,nextChapter,0);               
                }
            }
        }else{
            //首页
            _this.getDetails(_this.mediaId,0,0); 
        }
        
    }
    handlePrev(){//上一页
        let _this=this;
        _this.pageNumber=_this.pageNumber-1;//页码减1
        if(_this.chapter.pageIndex>0){
            //本单元的上一页
            let prevPageIndex=_this.chapter.pageIndex-1;//上一页的pageIndex
            _this.getDetails(_this.mediaId,_this.chapter.chapterID,prevPageIndex);
        }else{            
            let prevChapterID=_this.chapter.chapterID-1;//上一个单元id
            _this.ChapterIDs.forEach((item: { ChapterID: number; pageCount: number },index: any)=>{                
                if(item.ChapterID==prevChapterID){
                    if(item.pageCount>1){
                        //上一个单元的最后1页
                        let prevPageCount=item.pageCount-1;//最后一页的pageIndex
                        //console.log('上一个单元',prevChapterID,'最后一页的pageIndex',prevPageCount);
                        _this.getDetails(_this.mediaId,prevChapterID,prevPageCount);
                    }else{                        
                        //上一个单元的第1页
                        _this.getDetails(_this.mediaId,prevChapterID,0);
                    }                    
                }
            })
        }
        
    }
}
export default Gategory